package com.example.springboot.controller.asyncrequest;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/9/18 11:02
 */
@RestController
@RequestMapping("/async")
@Slf4j
public class AsyncRequestController {


    @GetMapping("/test")
    public String getString(HttpServletRequest request) {
        String a = request.getParameter("a");
        log.info("a = " + a);
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String a1 = request.getParameter("a");
            // null 因为当前这个请求已经被返回了，执行了 recycle 相关操作，queryMB 就是在这个时候没有的。
            log.info("a1 = " + a1);
        }).start();
        return "请求成功";
    }

    /**
     * request线程复用的正确打开方式
     *
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/test1")
    public String getString1(HttpServletRequest request, HttpServletResponse response) {
        AsyncContext asyncContext = request.startAsync(request, response);
        String a = request.getParameter("a");
        log.info("a = " + a);
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String a1 = request.getParameter("a");
            log.info("a1 = " + a1);
            asyncContext.complete();
        }).start();
        return "请求成功";
    }
}
